<script setup lang="ts">
/*
 * @description: 商品选择组件
 * @author:
 * @date: 2025-8-9
 * @version: V1.0.0
 */
import { dataPageApi, dataBatchDelApi } from '@/api/goods'
import type { ItemFormInt } from '@/api/goods/types'
import { usePage } from '@/hooks/system/useFramework'
import constants from '@/common/constant'

// 定义组件属性
interface Props {
  modelValue: ItemFormInt | null
  placeholder?: string
  disabled?: boolean
}

// 定义事件
interface Emits {
  (e: 'update:modelValue', value: ItemFormInt | null): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: null,
  disabled: false,
  placeholder: '请选择商品'
})

const emit = defineEmits<Emits>()

// 引用
const tableRef = ref()
const queryFormRef = ref()
const selectGoodsRef = ref()

// 数据状态
const dialogVisible = ref(false)
const selectedGoods = ref<ItemFormInt | null>(null)

// 查询参数
const queryParams = ref({
  keywords: '',
  goodType: '',
})

// 使用项目现有的usePage hook处理分页逻辑
const { queryPage, tableData, loading, handleQuery, handleResetQuery } = usePage<ItemFormInt>(
  dataPageApi,
  dataBatchDelApi,
  queryParams,
  queryFormRef,
  selectGoodsRef
)

// 计算属性：显示在输入框中的商品信息
const displayText = computed(() => {
  if (props.modelValue && props.modelValue.goodName) {
    return `${props.modelValue.goodName} (${props.modelValue.goodModel || '无型号'})`
  }
  return ''
})

// 打开选择对话框
const openDialog = () => {
  if(props.disabled) return
  dialogVisible.value = true
  selectedGoods.value = props.modelValue
  nextTick(() => {
    // 初始化数据
    handleQuery()
  })
}

// 选择商品
const handleSelectGoods = (row: ItemFormInt) => {
  selectedGoods.value = row
}

// 确认选择
const handleConfirm = () => {
  if (selectedGoods.value) {
    emit('update:modelValue', selectedGoods.value)
  }
  dialogVisible.value = false
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  selectedGoods.value = null
}

// 表格行点击事件
const handleRowClick = (row: ItemFormInt) => {
  tableRef.value?.setCurrentRow(row)
  handleSelectGoods(row)
}

const handleClear = () => {
  emit('update:modelValue', null)
}

defineExpose({
  openDialog
})
</script>

<template>
  <div class="select-goods">
    <el-input :disabled="props.disabled" v-model="displayText" :placeholder="placeholder" readonly @click="openDialog">
      <template #suffix>
        <el-icon v-if="displayText" style="cursor: pointer" @click="handleClear"><CircleClose /></el-icon>
        <el-icon v-else><ArrowDown /></el-icon>
      </template>
    </el-input>

    <!-- 商品选择对话框 -->
    <el-dialog v-model="dialogVisible" title="选择商品" width="1000px" @close="handleClose">
      <div class="select-goods__dialog">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-card shadow="never" class="search-card">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
              <el-form-item label="关键字" prop="keywords">
                <el-input v-model="queryParams.keywords" placeholder="商品名称/型号" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="商品类型">
                <Dict :code="constants.GOODS_TYPE" v-model="queryParams.goodType" placeholder="请选择商品类型" style="width: 200px" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <!-- 商品列表 -->
        <el-card shadow="never" class="data-table">
          <el-table ref="tableRef" v-loading="loading" fit height="450" highlight-current-row :data="tableData" border @row-click="handleRowClick">
            <el-table-column type="index" width="60" label="#" align="center" />
            <el-table-column label="商品名称" prop="goodName" min-width="120">
              <template #default="scope">
                <span class="goods-name">{{ scope.row.goodName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="型号" prop="goodModel" min-width="100" />
            <el-table-column label="规格" prop="goodSpecs" min-width="100" />
            <el-table-column label="单位" prop="goodUnit" width="80" align="center">
              <template #default="scope">
                <dict-label :code="constants.GOODS_UNIT" :model-value="scope.row.goodUnit" />
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="goodNum" width="80" align="center" />
            <el-table-column label="价格" prop="goodPrice" width="100" align="right">
              <template #default="scope">
                <span class="goods-price">¥{{ scope.row.goodPrice }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="成本价" prop="goodCostPrice" width="100" align="right">
              <template #default="scope">
                <span class="goods-cost-price">¥{{ scope.row.goodCostPrice }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="类型" prop="goodType" width="100" align="center">
              <template #default="scope">
                <dict-label :code="constants.GOODS_TYPE" :model-value="scope.row.goodType" />
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="queryPage.total > 0"
            layout="prev, pager, next, sizes, total"
            :total="queryPage.total"
            v-model:current-page="queryPage.pageNum"
            v-model:page-size="queryPage.pageSize"
            @current-change="handleQuery"
            @size-change="handleQuery"
          />
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :disabled="!selectedGoods" @click="handleConfirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.select-goods {
  width: 100%;

  &__dialog {
    .search-container {
      margin-bottom: 16px;

      .search-card {
        :deep(.el-card__body) {
          padding: 16px;
        }
      }
    }

    .data-table {
      :deep(.el-card__body) {
        padding: 0;
      }

      .el-table {
        margin-bottom: 16px;
      }

      .goods-name {
        font-weight: 500;
        color: #303133;
      }

      .goods-price {
        font-weight: 600;
        color: #f56c6c;
      }

      .goods-cost-price {
        color: #909399;
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding: 16px 0 0;
    border-top: 1px solid #ebeef5;
  }

  :deep(.el-dialog__body) {
    padding: 16px 20px 20px;
  }

  :deep(.el-dialog__header) {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
}
</style>
